﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Security.Policy;

namespace Aij1.Utils
{
    /// <summary>
    /// Web页面的分页类
    /// </summary>
    public class WebPager : DbPager
    {
        protected string PageName;
        public WebPager()
        {
            if (PageIndex <= 0)
            {
                int pageId = CommOp.ToInt(HttpContext.Current.Request.QueryString["Page"]);
                PageIndex = Math.Max(1, pageId);
            }

            PageName = RemovePageParam();
        }

        protected virtual string RemovePageParam()
        {
            string p = Regex.Replace(HttpContext.Current.Request.Url.PathAndQuery, @"[\?|&]Page=\d*", "");
            if (p.Contains('?'))
            {
                p = p + '&';
            }
            else
            {
                p = p + '?';
            }
            return p;
        }

        protected const string NextPageStr = "下一页";
        protected const string PrevPageStr = "上一页";
        protected const string CurrentPageNumFormat = "[{0}]";
        protected virtual string PageNumFormat { get { return "<a href='{0}Page={1}'>{2}</a>"; } }
        protected const int PageNumShow = 10;
        public override string ToString()
        {
            List<string> pList = new List<string>();
            pList.Add(string.Format("{0}/{1}页 {2}条", PageIndex, PageCount, RowNum));

            string pageNum = PrevPageStr;
            if (PageIndex > 1)
            {
                pageNum = String.Format(PageNumFormat, PageName, PageIndex - 1, pageNum);
            }
            pList.Add(pageNum);

            int endPage = Math.Min(PageCount, (PageIndex / PageNumShow + 1) * PageNumShow);
            int startPage = Math.Max(1, endPage - PageNumShow);

            foreach (int i in Enumerable.Range(startPage, endPage))
            {
                pageNum = String.Format(CurrentPageNumFormat, i);
                if (i != PageIndex)
                {
                    pageNum = String.Format(PageNumFormat, PageName, i, pageNum);
                }
                pList.Add(pageNum);
            }

            pageNum = NextPageStr;
            if (PageIndex < PageCount)
            {
                pageNum = String.Format(PageNumFormat, PageName, PageIndex + 1, pageNum);
            }
            pList.Add(pageNum);
            return String.Join(" ", pList.ToArray());
        }
    }
}
